<template>
  <div class="main">
    <section>
      <!--选择日期-->
      <el-form :inline=true class="demo-form-inline">
        <el-form-item label="选择月份">
          <el-date-picker
            v-model="choseMonth"
            type="month"
            value-format = "yyyy-MM"
            :picker-options="timeLimit"
            :clearable = false
            @change="getList('change')"
            placeholder="请选择月份">
          </el-date-picker>
        </el-form-item>
      </el-form>

      <!--上传数据表格-->
      <aside>交易记录上传</aside>
      <el-table
        :data="tableData"
        border
        :loading="listLoading"
        header-row-class-name="table-header"
        style="width: 100%; margin-bottom: 50px">
        <el-table-column
          label="名称">
          <template slot-scope="scope">
            <svg-icon v-if="scope.row.type === 1" icon-class="alipay" class="aliPay" />
            <svg-icon v-else-if="scope.row.type === 2" icon-class="wechat" class="weChat" />
            <img v-else src="../../assets/common/union_pay.png" class="union" />
            {{ scope.row.name }}
          </template>
        </el-table-column>
        <el-table-column
          label="最早交易时间">
          <template slot-scope="scope">
            <span>{{scope.row.earliestTime!=''?scope.row.earliestTime: '暂无数据' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="finalTime"
          label="最后交易时间">
          <template slot-scope="scope">
            <span>{{scope.row.finalTime!=''?scope.row.finalTime: '暂无数据' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="tradeNum"
          width="100"
          label="交易笔数">
          <template slot-scope="scope">
            <span>{{scope.row.tradeNum!=''?scope.row.tradeNum: '暂无数据' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="payPriceTotal"
          label="交易总额">
          <template slot-scope="scope">
            <span>{{scope.row.payPriceTotal!=''?scope.row.payPriceTotal: '暂无数据' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="status"
          width="80"
          label="状态">
          <template slot-scope="scope">
            <span v-if="scope.row.status === 10">处理完成</span>
            <span v-else-if="scope.row.status === 20">处理中...</span>
            <span v-else-if="scope.row.status === null">暂无</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="remark"
          min-width="180"
          label="处理结果">
          <template slot-scope="scope">
            <div class="result-text">{{scope.row.remark!=''?scope.row.remark: '暂无结果'}}</div>
            <span class="detail-text" v-if="scope.row.remark" @click="checkDetail(scope.row.remark)">详情</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button v-if="scope.row.status === 20" type="text" :loading="true">文件处理中</el-button>
            <el-button v-else @click="show(scope.row.type,scope.row.name)" type="text" size="small">上传文件</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- <el-button type="success" @click="onSubmit(choseMonth)">
        <span v-if="rebuild">重新生成对账单</span>
        <span v-else>生成新对账单</span>
      </el-button> -->
      <el-button type="primary" @click="getList('get')" plain>刷新上传处理结果</el-button>

      <el-dialog :title="fileTitle"
                 :before-close="handleClose"
                 :visible.sync="dialogFormVisible">
        <el-upload
          class="upload-demo"
          ref="upload"
          :action="upladUrl"
          name="file"
          :on-success="getUrl"
          :auto-upload="false"
          :limit='limitNum'>
          <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
          <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
        </el-upload>
        <!--<el-form multipart>-->
          <!--<el-form-item label="选择要上传的文件">-->
            <!--<input type="file" ref="file2"  @change="getFile" value="">-->
          <!--</el-form-item>-->
        <!--</el-form>-->
        <!--<div class="dialog-footer">-->
          <!--<el-button @click="dialogFormVisible = false">取 消</el-button>-->
          <!--<el-button type="primary" @click="handleClick(current)"  :loading="loading">-->
            <!--<span v-if="!loading">确定上传</span>-->
            <!--<span v-else>文件上传中</span></el-button>-->
        <!--</div>-->
      </el-dialog>
    </section>
  </div>
</template>

<script>

  import { uploadFile, getUploadList, getHistoryList, checkBills, creatBills, reCreatBills } from '@/api/reconciliation'

  export default {
    name: "uploadSalesFinance",
    data() {
      return {
        limitNum: 1,
        uploading: false,
        timer: null,
        rebuild: false,
        listLoading: true,
        timeLimit: {
          disabledDate(time) {
            var date = new Date();
            var year = date.getFullYear();
            var month = date.getMonth();
            if (month >= 1 && month <= 9) {
              month = "0" + month;
            }
            var currentdate = year.toString()  + month.toString();

            var timeyear = time.getFullYear();
            var timemonth = time.getMonth()+1;
            if (timemonth >= 1 && timemonth <= 9) {
              timemonth = "0" + timemonth;
            }
            var timedate = timeyear.toString() + timemonth.toString();
            return currentdate < timedate;
            // return time.getTime() > Date.now();
          }
        },
        fileTitle: '',
        current: 0,
        dialogFormVisible: false,
        loading: false,
        choseMonth: this.getLastMonth(),
        csvFile: '',
        history: [],
        backUp: [],
        tableData: [
          {
            name: '支付宝付款和退款',
            earliestTime: "",
            finalTime: "",
            tradeNum: '',
            payPriceTotal: '',
            status: null,
            remark: '',
            type: 1
          },
          {
            name: '微信付款和退款',
            earliestTime: "",
            finalTime: "",
            tradeNum: '',
            payPriceTotal: '',
            status: null,
            remark: '',
            type: 2
          },
          {
            name: '云闪付付款和退款',
            earliestTime: "",
            finalTime: "",
            tradeNum: '',
            payPriceTotal: '',
            status: null,
            remark: '',
            type: 3
          }
        ],
      }
    },
    created() {
      this.backUp = Object.assign([], this.tableData)
      this.getList()
    },
    methods: {

      // 关闭对话框的操作
      handleClose(done) {
        const mainImg = this.$refs.upload;
        mainImg.clearFiles()
        done()
      },

      // 上传文件到服务器
      submitUpload() {
        this.$refs.upload.submit();
      },

      // 获取上传后文件的地址
      getUrl(response, file, fileList) {
        this.csvFile = response.filePath
        this.handleClick(this.current)
      },

      // 获取当前时间
      getLastMonth() {
        let result = ''
        if(this.$route.query.time){
          result = this.$route.query.time
        } else {
          let date = new Date;
          let year = date.getFullYear();
          let month = date.getMonth() <10 ? '0'+date.getMonth(): date.getMonth();
          if(month === 0){
            year = year -1;
            month = 12;
          }
          result = year+"-"+month;
        }
        return result;
      },

      // 获取数据
      getList(val) {
        if(!this.$route.query.time && val === undefined){
          this.choseMonth = ''
          return
        }else if(this.choseMonth === '') {
          this.$message({
            message: '没有选择月份',
            type: 'error'
          })
          return
        }
        let arr = []
        let orgin = JSON.parse(JSON.stringify(this.backUp))
        let targetMonth =parseInt(this.choseMonth.replace('-', ''))
        getUploadList(targetMonth).then(res => {
          if(res.data.length === 0 ){
            this.tableData = this.backUp
            this.$message({
              message: '当前月份无上传记录',
              type: 'info'
            })
            this.rebuild = false
            return
          }
          for(const i in orgin){
            res.data.forEach(item => {
              if (orgin[i].type === item.type) {
                let title = orgin[i].name
                arr[i] = item
                arr[i].name = title
                orgin[i] = arr[i]
              }
            })
          }
          this.tableData = orgin
          this.$forceUpdate(this.tableData)
          this.listLoading = false
          if(val!=='upload'){
          this.$message({
            message: '查询完成',
            type: 'success'
          })
          }
          // this.rebuild = res.data.isGenerated
        }).catch(err => {
          this.listLoading = false
        })
      },


      // 拿到文件数据
      getFile(){
        this.csvFile = this.$refs.file2.files[0]
      },


      // 显示选择框
      show(type, name) {
        if(this.choseMonth === ''){
          this.$message({
            message: '请选择月份',
            type: 'error'
          })
          return
        }
        if(this.uploading){
          this.$message({
            message: '正在上传中，稍等',
            type: 'info'
          })
          return
        }
        this.fileTitle = '选择' + name + '文件'
        this.dialogFormVisible = true
        this.current = type
        if(this.$refs.file2 !== undefined){
          this.$refs.file2.value = ""
        }
      },

      // 生成对账单
      createStart(val) {
        // 判断微信、支付宝是否有当前月份交易记录，选是开始生成并提示：生成对账单预计需要XX分钟，您可以去其它操作，稍后过来下载
        let month = new Date(val).getMonth()+1
        let str = ''
        let building = false
        this.tableData.forEach(info => {
          let iMonth = new Date(info.earliestTime).getMonth()+1
          if ( iMonth != month) {
            str += info.name + '、'
          }
          if(info.status === 20){
            building = true
          }
        })
        if(building){
          this.$message({
            type: 'error',
            message: '正在生处理中，请等待处理完成再生成...'
          });
          return false
        } else {
          if (str !== '') {
            str = str.slice(0, str.length-1)
            this.$confirm('本次上传还缺少'+ str +', 是否继续生成?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              console.log('str', str)
              console.log('table', this.tableData)
              if(str.split('、').length >= this.tableData.length) {
                this.$message({
                  type: 'error',
                  message: '所有数据都为空，无法生成！请重新上传文件'
                });
                return false
              }
              creatBills({dateStr:val}).then(res => {
                this.$message({
                  type: 'success',
                  message: '生成对账单预计需要几分钟，您可以去做其它操作，稍后过来下载~'
                });
                this.getList()
              })
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消生成'
              });
            });
          } else {
            creatBills({dateStr:val}).then(res => {
              this.$message({
                type: 'success',
                message: res.msg || res.message
              });
              this.getList()
            })
          }
        }


      },

      printW(){
        console.log('chen')
        this.timer = setTimeout(() => {
          console.log('1')
        }, 1000)
      },

      // 轮询检查对账单是否生成
      repeatCall(){
        setTimeout(this.printW, 1000)
      },

      //  生成对账单的检验流程
      onSubmit(time){
        const choseDate = this.choseMonth
        if(choseDate === ''){
          this.$message({
            message: '请选择月份',
            type: 'error'
          })
          return
        }

         // 有了已存在的数据
        if (this.rebuild){
          this.$confirm('已有对账单是否继续生成', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            console.log('开始生成')
            this.createStart(time)
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消生成'
            });
          });
        } else {
          this.createStart(time)
        }
      },

      //  上传文件
      async handleClick(val){
        if(this.csvFile === ''){
          this.$message({
            message: '请先选择要上传的文件!',
            type: 'error'
          })
          return
        }
        let formData = new FormData();
        formData.append('file', this.csvFile);
        formData.append('type', val);
        formData.append('month', this.choseMonth.replace('-', ''));
        this.loading = true
        this.uploading = true
        uploadFile(formData).then(res => {
          this.dialogFormVisible = false
          this.loading = false
          this.$message({
            message: res.message || res.msg,
            type: 'success'
          })
          this.uploading = false
          const mainImg = this.$refs.upload;
          mainImg.clearFiles()
          this.getList('upload')
        }).catch(err => {
          this.$message({
            message: '上传失败，请重新上传',
            type: 'error'
          })
          this.uploading = false
          this.loading = false
        })
      },
      // 处理结果详情
      checkDetail(text) {
        this.$confirm(text, '', {
          confirmButtonText: '确定',
          showCancelButton: false,
          center: true
        })
      }
    }
  }
</script>

<style scoped>
  .main>section{
    padding: 24px;
    background: #fff;
  }
  .svg-icon, .union { width: 1.2em; height: 1.2em; vertical-align: middle }
  .aliPay { color: #00a1e9 }
  .weChat { color: #40b737 }
  .ali { background-color: #00a1e9 }
  .result-text{
    overflow: hidden;
    text-overflow:ellipsis; 
    white-space: nowrap;
  }
  .detail-text{
    color: #00a1e9;
    cursor: pointer;
  }
</style>
